package com.jing.service.impl;

import com.jing.mapper.ReadingRoomsMapper;
import com.jing.mapper.ReservationInfoMapper;
import com.jing.mapper.UserLogMapper;
import com.jing.mapper.UserMapper;
import com.jing.pojo.ReadingRooms;
import com.jing.pojo.ReservationInfo;
import com.jing.pojo.UserReservationInfo;
import com.jing.service.ReservationInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author 陈书憬
 * @version 1.0
 * 2024/9/20
 */
@Service
public class ReservationInfoServiceImpl implements ReservationInfoService {

    @Autowired
    private ReservationInfoMapper reservationInfoMapper;

    @Autowired
    private ReadingRoomsMapper readingRoomsMapper;

    @Autowired
    private UserLogMapper userLogMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void checkSeatAvailability(ReservationInfo reservationInfo) {
        reservationInfoMapper.checkSeatAvailability();
    }

    @Override
    public void add(ReservationInfo reservationInfo) {

        reservationInfo.setCreateTime(String.valueOf(LocalDateTime.now()));
        reservationInfoMapper.add(reservationInfo);
        UserReservationInfo userReservationInfo = new UserReservationInfo();
        userReservationInfo.setNames(reservationInfo.getName());

        userLogMapper.add(reservationInfo);
    }

    @Override
    public ReservationInfo findSeat(Integer id, Integer seatId) {
        ReservationInfo seat = reservationInfoMapper.findSeat(id, seatId);
        return seat;
    }

    @Override
    public List<Integer> findSeatButton(Integer id) {
        List<Integer> seatButton = reservationInfoMapper.findSeatButton(id);
        return seatButton;
    }

    @Override
    public List<String> findUserSeatStatus(Integer id) {
        List<String> userSeatStatus = reservationInfoMapper.findUserSeatStatus(id);
        return userSeatStatus;
    }

    @Override
    public List<ReservationInfo> findUserMsgById(Integer userId) {
        List<ReservationInfo> reservationInfoList = reservationInfoMapper.findUserMsgById(userId);
        return reservationInfoList;
    }

    @Override
    public void updateSignIn(Integer userId, String checkInTime) {
        reservationInfoMapper.updateSignIn(userId, checkInTime);
    }

    @Override
    public void updateSignOut(Integer userId, String checkOutTime) {
        reservationInfoMapper.updateSignOut(userId, checkOutTime);
    }

    @Override
    public void setSeatStatus(Integer userId, String reservationStatus) {

        reservationInfoMapper.setSeatStatus(userId, reservationStatus);
        // 更新状态，包含时间的情况
        userLogMapper.setSeatStatus(userId, reservationStatus);
    }

    @Override
    public void deleteUserInfo(Integer userId) {
        reservationInfoMapper.deleteUserInfo(userId);
    }

    @Override
    public void selectSeatStatus(Integer userId) {
        reservationInfoMapper.selectSeatStatus(userId);
    }

    @Override
    public void changeSeatMsg(ReservationInfo reservationInfo) {
        reservationInfoMapper.changeSeatMsg(reservationInfo);
    }

    @Override
    public List<ReservationInfo> findSeatTimes(Integer id, Integer seatId) {
        List<ReservationInfo> seatTimes = reservationInfoMapper.findSeatTimes(id, seatId);
        return seatTimes;
    }

    @Override
    public void addSensorSeat(String name, String time, String seatId, String username) {
        List<ReadingRooms> readingRoomsList = readingRoomsMapper.selectName(name);

        int userId = userMapper.selectIdByName(username);

        String type = readingRoomsList.get(0).getType();
        String floor = readingRoomsList.get(0).getFloor();
        String area = readingRoomsList.get(0).getArea();
        String nameId = String.valueOf(readingRoomsList.get(0).getId());


        // 使用 split 方法拆分
        String[] times = time.split("-");
        String startTime = times[0];
        String endTime = times[1];
        LocalDate today = LocalDate.now();

        ReservationInfo reservationInfo = new ReservationInfo();
        reservationInfo.setName(name);
        reservationInfo.setType(type);
        reservationInfo.setSeatId(Integer.valueOf(seatId));
        reservationInfo.setFloor(Integer.valueOf(floor));
        reservationInfo.setArea(area);
        //时间
        reservationInfo.setStartTime(startTime);
        reservationInfo.setEndTime(endTime);
        reservationInfo.setOptionDate(String.valueOf(today));
        reservationInfo.setReservationStatus("已预约");
        reservationInfo.setCreateTime(String.valueOf(LocalDateTime.now()));
        reservationInfo.setNameId(Integer.valueOf(nameId));
        reservationInfo.setUserId(userId);



        reservationInfoMapper.addSensorSeat(reservationInfo);

        userLogMapper.add(reservationInfo);
    }

    // 定时任务  对于已经过期的预约信息进行删除


    @Scheduled(fixedRate = 10000) // 每30分钟执行一次，单位为毫秒
//    @Scheduled(cron = "0 1,31 * * * ?")    // 使用cron表达式，每小时的第1分钟和第31分钟执行
    public void executeTask() {

        LocalDateTime now = LocalDateTime.now();    // 获取当前时间
        String nowDate = now.toLocalDate().toString(); // 获取当前日期

        List<ReservationInfo> reservationInfoList = reservationInfoMapper.selectDatetime(nowDate);
        processExpiredReservations(reservationInfoList, now);
    }

    private void processExpiredReservations(List<ReservationInfo> reservations, LocalDateTime now) {
        for (ReservationInfo reservation : reservations) {
            // 假设 reservation.getEndTime() 返回的是 HH:mm 格式的字符串
            LocalTime endTime = LocalTime.parse(reservation.getEndTime(), DateTimeFormatter.ofPattern("HH:mm"));

            // 将 LocalTime 转换为 LocalDateTime，使用当前日期
            LocalDateTime endDateTime = endTime.atDate(now.toLocalDate());

            if (now.isAfter(endDateTime)) {
                // 处理超时预约
                System.out.println("预约已超时，处理用户ID: " + reservation.getUserId());
                handleExpiredReservation(reservation); // 如果需要处理超时逻辑，请取消注释
            }
        }
    }


    private void handleExpiredReservation(ReservationInfo reservation) {
        String isCheckedIn = reservation.getCheckInTime();
        String isCheckedOut = reservation.getCheckOutTime();

        // 更新预约状态为已结束
        reservation.setReservationStatus("已结束");

        // 插入到预约信息记录表
        userLogMapper.add(reservation);

        // 获取用户当前分数
        int currentScore = userMapper.findUserById(reservation.getUserId());

        if (isCheckedIn != null && isCheckedOut != null) {
            // 正常签到签退 +1分
            System.out.println("签到签退正常");
            if (currentScore < 100) {
                userMapper.updateUserScore(reservation.getUserId(), currentScore + 1);
            }
        } else if (isCheckedIn == null && isCheckedOut == null) {
            // 未签到和签退 -10分  浪费资源
            int newScore = currentScore - 10;
            userMapper.updateUserScore(reservation.getUserId(), newScore);
            reservation.setReservationStatus("已过期");
            System.out.println("未签到和签退");
        } else {
            // 签到或者签退未完成 -5分
            int newScore = currentScore - 5;
            userMapper.updateUserScore(reservation.getUserId(), newScore);
            System.out.println("签到或者签退未完成");
        }

        // 删除该条座位预约记录
        reservationInfoMapper.deleteUserInfo(reservation.getUserId());
    }

}
